/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package adee.qrlogin;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import qrlogin.common.QRLoginParam;

/**
 *
 * @author adee
 */
public class AccountsDB extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 2;
    private static final String DATABASE_NAME = "qrlogin.db";
    private static final String ACCOUNTS_TABLE_NAME = "accounts";
    private static final String ACCOUNT_PARAMETERS_TABLE_NAME = "account_parameters";

    private static final String ACCOUNTS_TABLE_CREATE =
                "CREATE TABLE " + ACCOUNTS_TABLE_NAME + " (" +
                "id integer primary key autoincrement,"+
                "logined integer,"+
                "sessionid text not null,"+
                "link TEXT not null);";
    
    private static final String ACCOUNTS_PARAMETERS_TABLE_CREATE =
                "CREATE TABLE " + ACCOUNT_PARAMETERS_TABLE_NAME + " (" +
                "id integer primary key autoincrement,"+
                "aid integer, "+ // account id
                "name TEXT not null, " +
                "humanname TEXT not null,"+
                "value TEXT not null,"+
                "type TEXT not null); " ;


     private static final int ID =0;
     private static final int LOGINED =1;
     private static final int SESSIONID =2;
     private static final int LINK =3;
     private static final int AID =1;
     private static final int NAME =2;
     private static final int HUMANNAME =3;
     private static final int VALUE =4;
     private static final int TYPE =5;

     private void saveLoginParameters(Account account){

        for (qrlogin.common.QRLoginParam param: account.getLoginParameters().values()){
                ContentValues values = new ContentValues();
                values.put("aid", account.getId());
                values.put("name", param.getName());
                values.put("humanname", param.getHumanName());
                values.put("type", param.getType());
                values.put("value", param.getValue());
                this.getWritableDatabase().insert(ACCOUNT_PARAMETERS_TABLE_NAME, null,values);
        }

    }


    private HashMap<String,QRLoginParam> getLoginParameters(Account account){
        HashMap<String,QRLoginParam> parameters = new HashMap<String,QRLoginParam>();
        Cursor c = this.getReadableDatabase().query(ACCOUNT_PARAMETERS_TABLE_NAME,null,"aid=?",new String[]{String.valueOf(account.getId())}, null,null, null);
        while(c.moveToNext()){
            QRLoginParam param = new QRLoginParam(c.getString(NAME), c.getString(HUMANNAME), c.getString(TYPE));
            param.setValue(c.getString(VALUE));
            parameters.put(param.getName(),param);
            
        }
         c.close();
        return parameters;

    }

    public int newAccount(Account account){
        ContentValues values = new ContentValues();
        values.put("logined",account.isLogined());
        values.put("link", account.getLink());
        values.put("sessionid", account.getSessionId());
     
        int id = (int) this.getWritableDatabase().insert(ACCOUNTS_TABLE_NAME, null,values);
        account.setId(id);
        this.saveLoginParameters(account);
        return id;
    }

    public void deleteAccount(Account account){
        this.getWritableDatabase().delete(ACCOUNTS_TABLE_NAME,"id=?",new String[]{String.valueOf(account.getId())});
        this.getWritableDatabase().delete(ACCOUNT_PARAMETERS_TABLE_NAME,"aid=?",new String[]{String.valueOf(account.getId())});
    }



    public void updateAccount(Account account){
        ContentValues values = new ContentValues();
        values.put("logined",account.isLogined());
        values.put("link", account.getLink());
        values.put("sessionid", account.getSessionId());
        this.getWritableDatabase().update(ACCOUNTS_TABLE_NAME, values, "id=?", new String[]{String.valueOf(account.getId())});
        this.getWritableDatabase().delete(ACCOUNT_PARAMETERS_TABLE_NAME,"aid=?",new String[]{String.valueOf(account.getId())});
        this.saveLoginParameters(account);

    }

    public AccountsDB(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }




    public Account getAccount(int id){
        Account account=null;
        Cursor c = this.getReadableDatabase().query(ACCOUNTS_TABLE_NAME,null,"id=?",new String[]{String.valueOf(id)}, null,null, null);
        c.moveToFirst();
        if (c.getCount()>0){
          account = new Account(c.getInt(ID),c.getString(LINK),c.getString(SESSIONID),c.getInt(LOGINED));
          account.setLoginParameters(this.getLoginParameters(account));
        }
        c.close();
        return account;
    }

    public void saveAccount(Account account){
      if (account.isModified()){
          if (account.getId()==-1) { // new account
              this.newAccount(account);
          } else {
              this.updateAccount(account);
        }
      }

    }

    public Account getAccountByLink(String link){
        Account account = null;
        Cursor c = this.getReadableDatabase().query(ACCOUNTS_TABLE_NAME,null,"link=?",new String[]{link}, null,null, null);
        c.moveToFirst();
        if(c.getCount() >0) {
          account = new Account(c.getInt(ID),c.getString(LINK),c.getString(SESSIONID),c.getInt(LOGINED));
          account.setLoginParameters(this.getLoginParameters(account));
        }
        c.close();
        return account;
    }

    public List<Account> getAccounts(){
        Account account = null;
        ArrayList<Account> accounts = new ArrayList<Account>();
        Cursor c = this.getReadableDatabase().query(ACCOUNTS_TABLE_NAME,null,null,null, null,null, null);
        while(c.moveToNext()) {
          account = new Account(c.getInt(ID),c.getString(LINK),c.getString(SESSIONID),c.getInt(LOGINED));
          account.setLoginParameters(this.getLoginParameters(account));
          accounts.add(account);
        }
        c.close();
        return accounts;
    }
    public void saveAccounts(List<Account> accounts){
        for (Account account: accounts) this.saveAccount(account);
    }

    @Override
    public void onCreate(SQLiteDatabase sqld) {
        sqld.execSQL(ACCOUNTS_TABLE_CREATE);
        sqld.execSQL(ACCOUNTS_PARAMETERS_TABLE_CREATE);

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqld, int i, int i1) {

        
    }



}
